import 'dart:collection';
import 'dart:convert';
import 'package:auto_size_text/auto_size_text.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gif/gif.dart';
import '../bean/GemBean.dart';
import '../bean/HashModel.dart';
import '../bean/PopBean.dart';
import '../config/AppConst.dart';
import '../game/block.dart';
import '../sqflite/DBManager.dart';
import '../utils/AudioUtils.dart';
import '../utils/GamePageUtils.dart';
import '../utils/SpUtils.dart';
import '../bean/BlockBean.dart';
import '../main.dart';
import '../utils/CommUtils.dart';
import '../wight/Brik.dart';
import '../wight/Seting.dart';
import 'dart:math' as math;

import 'GamePage.dart';

///总行数
const GAME_PAD_MATRIX_H = 9;

///总列数
const GAME_PAD_MATRIX_W = 9;

//旅行 如果主要逻辑更改，应该和GamePage保持一致
class TravelGamePage extends StatefulWidget {
  TravelGamePage({
    Key? key,
  }) : super(key: key);
  @override
  State<TravelGamePage> createState() => GamePageState();
}

///所有数据
List<List<BlockBean>> _data = [];

//三个随机模块
List<Block> _randowList = [];

//给将要满足消分的方格添加蒙版，
List<List<BlockBean>> mengdata = [];

//棋牌背景图左右内边距
const double bgPaddingSize = 10;

//棋盘内边距
double checkerboardSizeLeft = 8.5;

//棋盘方格默认背景
const String defaultBg = "assets/images/default_square.png";
//棋盘方格特殊背景
const String specialBg = "assets/images/special_square.png";

//宝石图片
const ListGemImg = [
  // "assets/images/gem1.png",
  "assets/gem/gem111.png",
  "assets/images/gem2.png",
  "assets/gem/gem112.png",
  "assets/images/gem3.png",
  "assets/gem/gem113.png",
  "assets/images/gem4.png",
  "assets/images/gem5.png",
  "assets/images/gem6.png",
  "assets/gem/gem114.png",
  "assets/images/gem7.png",
  "assets/images/gem8.png",
  "assets/images/gem9.png",
  "assets/gem/gem115.png",
  // "assets/images/gem10.png",
  "assets/images/gem11.png",
  "assets/images/gem12.png",
];

//8-15个随机宝石数量
const scoreList = [8, 9, 10, 11, 12, 13, 14, 15];

class GamePageState extends State<TravelGamePage> with RouteAware {
  //当前积分数量
  int? currentScore = 0;
  int? originalCurrentScore = 0;
  bool isGem = false; //true当前为宝石
  int? grade = 1; //当前等级

  @override
  void initState() {
    _data.clear();
    //true继续游戏挑战的话
    grade = SpUtils.getInstance()?.getInt2(AppConst.grade);


    _isvoice = SpUtils.getInstance()!.getBool2(AppConst.voice)!;
    _isBGvoice = SpUtils.getInstance()?.getBool2(AppConst.bgvoice);
    String? randowString =
        SpUtils.getInstance()?.getString(AppConst.travelrandomList);
    var continueGame =
        SpUtils.getInstance()?.getString(AppConst.trvelContinueGame);
    if (!CommUtils.validateInput(continueGame) ||
        !CommUtils.validateInput(randowString)) {
      startNewGame();
      return;
    }
    //当期积分
    if (grade! % 2 == 0) {
      startNewGame();
      //偶数为宝石
      var travelgemList =
          SpUtils.getInstance()?.getString(AppConst.travelgemList);
      var travelgemCopyList =
          SpUtils.getInstance()?.getString(AppConst.travelgemCopyList);
      //获取宝石种类
      //用户通关后，点击不用了，这里为null的
      if (!CommUtils.validateInput(travelgemList) ||
          !CommUtils.validateInput(travelgemCopyList)) {
        //没有值的话
        startNewGame();
        return;
      }

      isGem = true;
      gemList.clear();
      CopaygemList.clear();
      List list = json.decode(travelgemList!);

      for (var item in list) {
        var gemBean = GemBean.fromJson(item);
        gemList.add(gemBean);
      }

      List list2 = json.decode(travelgemCopyList!);
      for (var item in list2) {
        var gemBean = GemBean.fromJson(item);
        CopaygemList.add(gemBean);
      }
    } else {
      currentScore =
          SpUtils.getInstance()?.getInt(AppConst.travelContinueScore);
      originalCurrentScore =
          SpUtils.getInstance()?.getInt(AppConst.originalCurrentScore);
    }

    //棋盘
    List list = json.decode(continueGame!);
    for (var item2 in list) {
      List<BlockBean> d = (item2 as List<dynamic>)
          .map((e) => BlockBean.fromJson(e as Map<String, dynamic>))
          .toList();
      _data.add(d);
    }

    //三个底部随机
    List randowlist = json.decode(randowString!);
    _randowList = randowlist.map((e) => Block.fromJson(e)).toList();

    //查询被移除的随机木块
    var users = DBManager().getDBInfo(3);
    users.then((value) {
      if (value.length > 0) {
        for (HashModel item in value) {
          rondowRemowMap[item.onclickPositon] = "ddddd";
        }
        //这个要计时刷新下，因为是async
        setState(() {});
      }
    });

    //如果数组里的元素是int或者String，用List.from是没问题的。深拷贝
    mengdata = CommUtils.copyWithList(_data);

    startPLayBgVocie();
    //build完成后的回调
    // SchedulerBinding.instance?.addPostFrameCallback((_) {
    //   print("页面加载完了");
    // });

    super.initState();
  }

  bool? _isBGvoice = true; //背景音乐
  bool? isFisrtVociePlay = false;
  bool? _isvoice;

  //开始新游戏
  void startNewGame() {
    _data.clear();
    _randowList.clear();
    mengdata.clear();
    CopaygemList.clear();
    gemList.clear();

    startPLayBgVocie();

    //8到15个随机
    for (int i = 0; i < GAME_PAD_MATRIX_H; i++) {
      List<BlockBean> _newdata = [];
      for (int j = 0; j < GAME_PAD_MATRIX_W; j++) {
        BlockBean bean = BlockBean();
        //第一竖排
        if (i >= 0 && i <= 2) {
          //横排
          if (j >= 3 && j <= 5) {
            bean.defaultImg = specialBg;
          } else {
            bean.defaultImg = defaultBg;
          }
          //第二竖排
        } else if (i >= 3 && i <= 5) {
          //横排
          if (j >= 0 && j <= 2) {
            bean.defaultImg = specialBg;
          } else if (j >= 6 && j <= 8) {
            bean.defaultImg = specialBg;
          } else {
            bean.defaultImg = defaultBg;
          }
          //第三竖排
        } else if (i >= 6 && i <= 8) {
          //横排
          if (j >= 3 && j <= 5) {
            bean.defaultImg = specialBg;
          } else {
            bean.defaultImg = defaultBg;
          }
        } else {
          bean.defaultImg = defaultBg;
        }

        _newdata.add(bean);
      }

      _data.add(_newdata);
    }

    if (grade == 1) {
      isGem = false;
      currentScore = 50;
    } else if (grade == 3) {
      isGem = false;
      currentScore = 100;
    } else if (grade == 5) {
      isGem = false;
      currentScore = 125;
    } else if (grade == 7) {
      isGem = false;
      currentScore = 150;
    } else if (grade == 9) {
      isGem = false;
      currentScore = 175;
    } else if (grade == 11) {
      isGem = false;
      currentScore = 200;
    } else {
      //宝石类
      isGem = true;
      if (grade == 2) {
        addGemList(2, 3, -1, -1);
      } else if (grade == 4) {
        addGemList(3, -1, 3, 2);
      } else if (grade == 6) {
        addGemList(4, -1, 3, 4);
      } else if (grade == 8) {
        addGemList(4, 3, -1, -1);
      } else if (grade == 10) {
        addGemList(5, 3, -1, -1);
      } else if (grade == 12) {
        addGemList(5, 4, -1, -1);
      }

      for (var item in gemList) {
        GemBean bean = GemBean();
        bean.gemCount = item.gemCount;
        bean.img = item.img;
        CopaygemList.add(bean);
      }

      //宝石再棋盘上的排列
      _data = GamePageUtils().setTravelGem(_data, gemList);
    }

    //获取随机三个模块
    getRoundList();
    //如果数组里的元素是int或者String，用List.from是没问题的。深拷贝
    mengdata = CommUtils.copyWithList(_data);
    //设置原始分数
    if (!isGem) {
      SpUtils.getInstance()
          ?.setInt(AppConst.originalCurrentScore, currentScore!);
      originalCurrentScore = currentScore;
    } else {
      SpUtils.getInstance()
          ?.setString(AppConst.travelgemCopyList, json.encode(CopaygemList));
    }
  }

//宝石集合
  List<GemBean> gemList = [];
  List<GemBean> CopaygemList = [];

  void addGemList(int count, int everyCout, int startCount, int endCount) {
    HashMap<int, int> map = HashMap();
    for (int o = 0; o < count; o++) {
      var i = math.Random().nextInt(ListGemImg.length);
      if (map[i] != null) {
        while (true) {
          var nextInt = math.Random().nextInt(ListGemImg.length);
          if (nextInt != i) {
            i = nextInt;
            break;
          }
        }
      }
      map[i] = i;
      var gemBean = GemBean();
      gemBean.img = ListGemImg[i];
      if (startCount != -1 && endCount != -1) {
        if (o == count - 1) {
          //最后一个的话
          gemBean.gemCount = endCount;
        } else {
          gemBean.gemCount = startCount;
        }
      } else {
        gemBean.gemCount = everyCout;
      }

      gemList.add(gemBean);
    }
  }

  bool isEndGame = false; //true结束游戏
/**
 * 查询是否有不满足填充情况的随机木块 isreduction=true时，当开始不满足填充时，到被消分后，有可能就满足填充了，所以这里需要处理一下。
 */
  void qrueyUnableTOfill(bool isreduction) {
    var qruey = GamePageUtils.qruey(_randowList, _data, rondowRemowMap);
    // print("查询出${qruey.length}");
    //下方方块显示的数量=总随机方块-被隐藏的数量
    int showCount = _randowList.length - rondowRemowMap.length;
    //  print("剩多少个还在显示${showCount}");
    //无法拖动的数量
    int noDragCount = 0;
    for (int i = 0; i < _randowList.length; i++) {
      if (qruey[i] != null) {
        // print("当前无法拖动positon${i}");
        //证明此下方的postop是不满足填充情况的
        for (var item in _randowList[i].shape) {
          for (var item2 in item) {
            if (item2.normal == 1) {
              item2.normal = 2;
            }
          }
        }
        noDragCount = noDragCount + 1;

        _randowList[i].drag = 1; //不允许拖动

      } else {
        if (isreduction && rondowRemowMap[i] == null) {
          // print("当前变更的positon${i}");
          _randowList[i].drag = 0; //允许拖动
          for (var item in _randowList[i].shape) {
            for (var item2 in item) {
              if (item2.normal != 0) {
                item2.normal = 1;
              }
            }
          }
        }
      }
    }

    if (noDragCount >= _randowList.length || noDragCount >= showCount) {
      //无法拖动的数量 大于3 个或者 大于等于显示的数量
      isEndGame = true;
      GamePageUtils().TravelGameFail(
        context,
        currentScore!,
        isGem,
        gemList: gemList,
        callbacks: (selectIndex) {
          //游戏结束后，再进行新游戏的设置
          startNewGame();
          setState(() {
            isEndGame = false;
          });
        },
      );
    }
  }

/**
 * 播放背景音乐
 */
  void startPLayBgVocie() {
    if (_isBGvoice!) {
      if (isFisrtVociePlay == false) {
        //没有播放的话
        AudioUtils.getInstance()?.playLood2("tarvel_bgm.mp3", 0.4);
        isFisrtVociePlay = true;
      } else {
        AudioUtils.getInstance()?.resume();
      }
    } else {
      AudioUtils.getInstance()?.pause();
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context)!);
  }

  @override
  void didPushNext() {
    //暂停，类似 android的onpause
    // pause();
  }

  void pauseOrResume() {
    //重新看到，类似 android的onpResume
  }

  @override
  void dispose() {
    if (!isEndGame) {
      // 游戏没结束时
      if (!isGem) {
        SpUtils.getInstance()
            ?.setInt(AppConst.travelContinueScore, currentScore!);
      } else {
        SpUtils.getInstance()
            ?.setString(AppConst.travelgemList, json.encode(gemList));
      }

      //转为json保存
      SpUtils?.getInstance()
          ?.setString(AppConst.trvelContinueGame, json.encode(_data));
      //存三个随机
      if (rondowRemowMap.isNotEmpty) {
        rondowRemowMap.forEach((key, value) {
          HashModel hashModel = HashModel();
          hashModel.onclickPositon = key;
          hashModel.type = 3;
          DBManager().insertHashModel(hashModel);
        });
      } else {
        DBManager().deletaHashModelAll(3);
      }

      SpUtils?.getInstance()
          ?.setString(AppConst.travelrandomList, json.encode(_randowList));
    }

    routeObserver.unsubscribe(this);
    super.dispose();
  }

  Offset offsetA = Offset(0, 0); //按钮的初始位置

  GlobalKey anchorKey = GlobalKey();
  GlobalKey anchorKey2 = GlobalKey();

  /**
   * 手动监听物理返回键
   */
  Future<bool> _requestPop() {
    // if (Navigator.canPop(context)) {
    //   if (!isEndGame) {
    //     Navigator.pop(context);
    //   }
    // } else {
    //   if (!isEndGame) {
    //     SystemNavigator.pop();
    //   }
    // }
    return Future.value(!isEndGame);
  }

  @override
  Widget build(BuildContext context) {
    Size size = CommUtils.getSize(context);
    double width = CommUtils.getWidth(context);
    double hight = CommUtils.getHeight(context);
    return WillPopScope(
        //增加返回键监听
        onWillPop: _requestPop, //增加返回键监听
        child: Scaffold(
          //字就没有黄色双横线了
          body: Container(
            width: CommUtils.getWidth(context),
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/bg.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: Stack(
              children: [
                //第一次Gif有延迟，所以这里预加载
                Gif(
                  width: 0,
                  height: 0,
                  image: AssetImage(
                    "assets/gif/1xg.gif",
                  ),
                  autostart: Autostart.once,
                ),
                Padding(
                  padding:
                      EdgeInsets.only(left: width * 0.02, right: width * 0.02),
                  child: Column(
                    children: [
                      Image.asset('assets/images/top_leaves.png',
                          width: double.infinity, fit: BoxFit.fill),
                      SizedBox(
                        height: size.height * 0.02,
                      ),
                      //分数
                      getTop(width, hight),
                      Expanded(
                        child: SingleChildScrollView(
                          child: getCheckerboard(),
                        ),
                      )
                    ],
                  ),
                ),
                Stack(
                  children: addshow.map((list) {
                    return Positioned(
                      left: list.offset!.dx,
                      bottom: list.offset!.dy + 10,
                      child: Gif(
                        width: size.width * 0.96,
                        height: size.width * 1.2,
                        image: AssetImage(
                          "assets/gif/1xg.gif",
                        ),
                        autostart: Autostart.once,
                      ),
                    );
                  }).toList(),
                ),
                Align(
                  alignment: Alignment.bottomCenter,
                  child: Image.asset('assets/images/botton_.png',
                      width: double.infinity,
                      height: hight * 0.09,
                      fit: BoxFit.fill),
                )
              ],
            ),
          ),
        ));
  }

  /**
     * 棋盘布局
     */
  GlobalKey rootWidgetKey = GlobalKey();
  Widget getCheckerboard() {
    final size = MediaQuery.of(context).size;
    final width = size.width;
    final height = size.height;
    checkerboardSizeLeft = width * 0.027;
    //需要截图的布局
    return RepaintBoundary(
        key: rootWidgetKey,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                //棋盘
                Container(
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/images/checkerboard.png'),
                      fit: BoxFit.contain,
                    ),
                  ),
                  alignment: Alignment.center,
                  child: Padding(
                    padding: EdgeInsets.only(
                        top: height * 0.01,
                        bottom: height * 0.02, //如果Container上面设置了高度，这离没用了
                        left: checkerboardSizeLeft,
                        right: width * 0.03),
                    child: Column(
                      key: anchorKey,
                      children: _data
                          .asMap()
                          .map((i, e) {
                            return MapEntry(
                                i,
                                Row(
                                  children: e
                                      .asMap()
                                      .map((i2, e) {
                                        return MapEntry(
                                            i2,
                                            BackgroundBrik.normal(
                                              e,
                                              bgChangelist,
                                              scoreChangelist,
                                              true,
                                              i,
                                              i2,
                                            ));
                                      })
                                      .values
                                      .toList(),
                                ));
                          })
                          .values
                          .toList(),
                    ),
                  ),
                ),

                CommUtils.getISWidth(width, height)
                    ? Expanded(
                        child: SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: Container(
                          width: 500,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage(
                                  'assets/images/checkerboard_bottom.png'),
                              fit: BoxFit.fill,
                            ),
                          ),
                          alignment: Alignment.center,
                          child: _createGridView(height, width),
                        ),
                      ))
                    : Text("")
              ],
            ),
            CommUtils.getISWidth(width, height)
                ? Text("")
                : Stack(
                    children: [
                      GamePageUtils().getCheckBooton(height),
                      _createGridView(height, width),
                    ],
                  )
          ],
        ));
  }

  void getRoundList() {
    rondowRemowMap.clear();
    _randowList = Block.getRandom(3, gemList: gemList, isgem: isGem);
  }

  int onclickPositon = -1; //触摸的positon

  //顶部
  Widget getTop(double width, double hight) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        GestureDetector(
          onTap: (() {
            Navigator.pop(context);
          }),
          child: Image.asset('assets/images/back.png',
              width: hight * 0.06, height: hight * 0.06, fit: BoxFit.fill),
        ),
        Expanded(
          child: Container(
              margin: CommUtils.getISWidth(width, hight)
                  ? EdgeInsets.only(left: width * 0.25, right: width * 0.25)
                  : EdgeInsets.only(
                      left: isGem ? width * 0.07 : width * 0.2,
                      right: isGem ? width * 0.07 : width * 0.2),
              padding: EdgeInsets.only(
                left: width * 0.01,
                right: width * 0.01,
                bottom: isGem ? width * 0.01 : width * 0.04,
                top: isGem ? 0 : width * 0.04,
              ),
              // height: hight * 0.2,
              decoration: BoxDecoration(
                image: DecorationImage(
                    image: AssetImage('assets/images/history.png'),
                    fit: BoxFit.fill),
              ),
              alignment: Alignment.center,
              child: isGem //是宝石的话
                  ? Wrap(
                      children: [
                        GridView.builder(
                            itemCount: gemList.length,
                            shrinkWrap: true,
                            padding: EdgeInsets.only(top: 0),
                            gridDelegate:
                                SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: gemList.length,
                              //  mainAxisSpacing: ScreenUtil().setHeight(10), //每行间距
                              //  crossAxisSpacing: ScreenUtil().setWidth(10), //交叉轴每行间距
                            ),
                            itemBuilder: (context, index) {
                              return Container(
                                  child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.center,
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Stack(
                                    children: [
                                      Image.asset(gemList[index].img,
                                          width: ScreenUtil().setWidth(20),
                                          height: ScreenUtil().setHeight(20),
                                          fit: BoxFit.contain),
                                      gemList[index].gemCount <= 0
                                          ? Container(
                                              width: ScreenUtil().setWidth(20),
                                              height:
                                                  ScreenUtil().setHeight(20),
                                              color: //透明色
                                                  Colors.white.withOpacity(0.4),
                                            )
                                          : Text(""),
                                    ],
                                  ),
                                  SizedBox(
                                    height: 5,
                                  ),
                                  AutoSizeText(
                                    '${gemList[index].gemCount}',
                                    style: TextStyle(
                                      fontWeight: FontWeight.bold,
                                      fontSize: ScreenUtil().setSp(15),
                                      color: Color(0xffffffff),
                                      height: 0.7,
                                    ),
                                    maxLines: 1,
                                    textAlign: TextAlign.center,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ],
                              ));
                            })
                      ],
                    )

                  //顶部宝石
                  : Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        AutoSizeText(
                          '${currentScore}',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: ScreenUtil().setSp(15),
                            color: Color(0xffffffff),
                            height: 0.7,
                          ),
                          maxLines: 1,
                          textAlign: TextAlign.center,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    )),
        ),
        GestureDetector(
          onTap: (() {
            AudioUtils.getInstance()?.play("seting_.mp3");
            /**
         * 设置弹窗
           */
            showGeneralDialog(
                context: context,
                pageBuilder: (context, anim1, anim2) {
                  return Text("");
                },
                // barrierColor: Colors.grey.withOpacity(.4), // Dialog 的背景色
                barrierDismissible: true, //控制 Dialog 是否消失
                barrierLabel: "",
                transitionDuration: Duration(milliseconds: 200),
                transitionBuilder: (context, anim1, anim2, child) {
                  return Transform.scale(
                    scale: anim1.value,
                    child: Dialog(
                      backgroundColor: Colors.transparent,
                      child: Seting(
                        isReStart: true,
                        callback: (e) {
                          _isvoice =
                              SpUtils.getInstance()?.getBool2(AppConst.voice);
                          _isBGvoice =
                              SpUtils.getInstance()?.getBool2(AppConst.bgvoice);
                          if (e == 8) {
                            //重新开始游戏
                            startNewGame();
                          } else {
                            if (_isBGvoice == false) {
                              AudioUtils.getInstance()?.pause();
                            } else {
                              startPLayBgVocie();
                            }
                          }
                          if (e == 8) {
                            //重新开始游戏
                            startNewGame();
                          }

                          print("回调刷新");
                          setState(() {});
                        },
                      ),
                    ),
                  );
                });
          }),
          child: Image.asset('assets/images/seting.png',
              width: hight * 0.06, height: hight * 0.06, fit: BoxFit.fill),
        )
      ],
    );
  }

  //消分弹窗
  List<PopBean> addshow = [];

/**
 * 底部三个随机    底部三个图标不能再下去了，底部始终有空白 crossAxisCount: 2,就可以到底部，不知道怎么设置
 */
  Widget _createGridView(double screenhight, double screenwight) {
    return GridView.builder(
      itemCount: _randowList.length,
      shrinkWrap: true,
      padding: EdgeInsets.only(top: 0),
      physics: NeverScrollableScrollPhysics(), //触摸可以
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        //  mainAxisSpacing: ScreenUtil().setHeight(10), //每行间距
        //  crossAxisSpacing: ScreenUtil().setWidth(10), //交叉轴每行间距
      ),
      itemBuilder: (context, index) {
        //隨機初始化
        List<List<BlockBean>> initialRandom = [];
        for (int i = 0; i < maxHight; i++) {
          initialRandom.add(
            List.filled(maxWidth, BlockBean()),
          );
        }

        for (int i = 0; i < _randowList[index].shape.length; i++) {
          for (int j = 0; j < _randowList[index].shape[i].length; j++) {
            initialRandom[i][j] = _randowList[index].shape[i][j];
          }
        }
        //   return _randowList[index].drag!=0?Text("牛逼") :

        return Draggable<Block>(
          //可以同时拖拽个数
          maxSimultaneousDrags: _randowList[index].drag == 0 ? 1 : 0, //等于0时允许拖
          // 当前组件的数据
          data: _randowList[index],
          feedback: getItem(initialRandom, FixCount1, true, index),
          //拖动过程中，在原来位置停留的Widget，设定这个可以保留原本位置的残影，如果不需要可以直接设置为Container()
          childWhenDragging: Container(),
          child: getItem(initialRandom, FixCount5, false, index),
          onDragStarted: () {
            onclickPositon = index;
          },

          //   ignoringFeedbackSemantics: false,
          onDragEnd: (DraggableDetails details) {
            scoreChangelist.clear();
            if (bgChangelist.length > 0) {
              if (_isvoice!) {
                final i = math.Random().nextInt(inputboardList.length);
                AudioUtils?.getInstance()?.play(inputboardList[i]);
              }
              setState(() {
                //证明开始符合填充逻辑  ,此逻辑更改棋盘的填充背景
                for (int i = 0; i < bgChangelist.length; i++) {
                  HashMap map = bgChangelist[i];
                  int xpositon = map.keys.first;
                  //  print("横向索引:${map.keys.first}");
                  // print("shu索引:${map.values.first.toString()}");
                  HashMap<int, BlockBean> map2 = map.values.first;
                  int ypositon = map2.keys.first;
                  //这里只需替换这两个即可，不能全部替换。不然默认棋盘图片也被替换了。
                  _data[xpositon][ypositon].normal = map2.values.first.normal;
                  if (map2.values.first.gem > 0) {
                    print(
                        "替换了x${xpositon},y${ypositon},gem=${map2.values.first.gem}");
                  }
                  _data[xpositon][ypositon].gem = map2.values.first.gem;
                  _data[xpositon][ypositon].img = map2.values.first.img;
                }
                //拖动已经超过3个了就重新获得随机木块。 目的是为了记录当前拖动方块的 ,所以可以为任意值。
                rondowRemowMap[onclickPositon] = "ddddd";
                shine = false; //表示不是闪耀
              });
              clearMap();
              onclickPositon = -1;
              // 延时500毫秒执行执行 查看是否满足消分
              Future.delayed(Duration(milliseconds: 500), () {
                int currentIntegral1 = addScore(true, _data);

                if (xtop1.length > 2) {
                  //   if (xtop2Have || xmiddle1Have) {
                  //上次刚好消了的话
                  currentIntegral1 = currentIntegral1 + 1;
                  //  }
                  xtop1Have = true;
                } else {
                  xtop1Have = false;
                }

                if (xtop2.length > 2) {
                  //   if (xtop1Have || xtop3Have || xmiddle2Have) {
                  //上次刚好消了的话
                  currentIntegral1 = currentIntegral1 + 1;
                  //  }
                  xtop2Have = true;
                } else {
                  xtop2Have = false;
                }

                if (xtop3.length > 2) {
                  // if (xtop2Have || xmiddle3Have) {
                  //上次刚好消了的话
                  currentIntegral1 = currentIntegral1 + 1;
                  //  }
                  xtop3Have = true;
                } else {
                  xtop3Have = false;
                }

                if (xmiddle1.length > 2) {
                  // isRefresh = true;
                  // if (xtop1Have || xmiddle2Have || xbottom1Have) {
                  //上次刚好消了的话
                  currentIntegral1 = currentIntegral1 + 1;
                  // }
                  xmiddle1Have = true;
                } else {
                  xmiddle1Have = false;
                }

                if (xmiddle2.length > 2) {
                  //    if (xtop2Have ||
                  //       xmiddle1Have ||
                  //     xmiddle3Have ||
                  //    xbottom2Have) {
                  //上次刚好消了的话
                  currentIntegral1 = currentIntegral1 + 1;
                  //  }
                  xmiddle2Have = true;
                } else {
                  xmiddle2Have = false;
                }
                if (xmiddle3.length > 2) {
                  //    if (xtop3Have || xmiddle2Have || xbottom3Have) {
                  //上次刚好消了的话
                  currentIntegral1 = currentIntegral1 + 1;
                  //  }
                  xmiddle3Have = true;
                } else {
                  xmiddle3Have = false;
                }

                if (xbottom1.length > 2) {
                  // if (xmiddle1Have || xbottom2Have) {
                  //上次刚好消了的话
                  currentIntegral1 = currentIntegral1 + 1;
                  //   }
                  xbottom1Have = true;
                } else {
                  xbottom1Have = false;
                }

                if (xbottom2.length > 2) {
                  //  if (xmiddle2Have || xbottom1Have || xbottom3Have) {
                  //上次刚好消了的话
                  currentIntegral1 = currentIntegral1 + 1;
                  //  }
                  xbottom2Have = true;
                } else {
                  xbottom2Have = false;
                }
                if (xbottom3.length > 2) {
                  // if (xmiddle3Have || xbottom2Have) {
                  //上次刚好消了的话
                  currentIntegral1 = currentIntegral1 + 1;
                  //   }
                  xbottom3Have = true;
                } else {
                  xbottom3Have = false;
                }

                if (isGem) {
                  //宝石的话并且消分了

                  if (isHaveXiao && pickUpMap.length > 0) {
                    int sucessCount = 0;
                    bool isgetVoice = false;
                    for (int i = 0; i < gemList.length; i++) {
                      if (pickUpMap[i] != null) {
                        isgetVoice = true;
                        //证明刚好消分的有此宝石
                        var gemCount = gemList[i].gemCount;
                        if (gemCount - pickUpMap[i]! <= 0) {
                          gemList[i].gemCount = 0;
                        } else {
                          gemList[i].gemCount = gemCount - pickUpMap[i]!;
                        }
                      }
                      //   print("党庆剩余${i},${gemList[i].gemCount}");
                      if (gemList[i].gemCount <= 0) {
                        sucessCount = sucessCount + 1;
                      }
                    }

                    if (sucessCount >= gemList.length) {
                      //表示完成收集，进入下一个等级
                      isEndGame = true;
                    } else {
                      if (isgetVoice && _isvoice!) {
                        final i = math.Random().nextInt(getSoreList.length);
                        AudioUtils.getInstance()?.play(getSoreList[i]);
                      }
                    }
                  }
                } else {
                  //  print("本次横竖排的个数${currentIntegral1}");
                  //积分的形式

                  if (currentIntegral1 > 0) {
                    // print("上次连接次数${adjacentMultiple}");
                    adjacentMultiple = adjacentMultiple + currentIntegral1;
                    //  print("本次连接次数${currentIntegral1}");
                    int thisScore = 9 * adjacentMultiple;
                    currentScore = currentScore! - thisScore;
                    if (currentScore! <= 0) {
                      currentScore = 0;
                      isEndGame = true;
                    } else {
                      if (_isvoice!) {
                        final i = math.Random().nextInt(getSoreList.length);
                        AudioUtils.getInstance()?.play(getSoreList[i]);
                      }
                    }
                  } else {
                    adjacentMultiple = 0;
                  }
                }

                // if (gemCountAll > 0) {
                //   currentScore = currentScore! - gemCountAll;
                //   isEndGame = (currentScore! <= 0);
                // }

                //测试
                // GamePageUtils().TravelGameFail(
                //   context,
                //   currentScore!,
                //   isGem,
                //   gemList: gemList,
                //   callbacks: (selectIndex) {
                //     //游戏结束后，再进行新游戏的设置
                //     startNewGame();
                //     setState(() {
                //       isEndGame = false;
                //     });
                //   },
                // );

                    //测试
                  // GamePageUtils().travelEndGame(
                  //     context, originalCurrentScore!, isGem, grade!,
                  //     gemList: CopaygemList, callbacks: (index) {
                  //   grade = index;
                  //   startNewGame();
                  //   setState(() {
                  //     isEndGame = false;
                  //   });
                  // });

                if (isEndGame) {
                  //成功完成游戏
                  GamePageUtils().travelEndGame(
                      context, originalCurrentScore!, isGem, grade!,
                      gemList: CopaygemList, callbacks: (index) {
                    grade = index;
                    startNewGame();
                    setState(() {
                      isEndGame = false;
                    });
                  });
                } else {
                  if (rondowRemowMap.isNotEmpty) {
                    //查询剩下的随机木块是否允许被拖动
                    if (rondowRemowMap.length >= ronudCOunt) {
                      //获取随机三个模块
                      getRoundList();
                      qrueyUnableTOfill(false);
                    } else {
                      qrueyUnableTOfill(isHaveXiao);
                    }
                  }
                }

                if (xtop1Have) {
                  _addNiceList(0, 3, 0, 3);
                }
                if (xtop2Have) {
                  _addNiceList(3, 6, 0, 3);
                }
                if (xtop3Have) {
                  _addNiceList(6, 9, 0, 3);
                }
                if (xmiddle1Have) {
                  _addNiceList(0, 3, 3, 6);
                }
                if (xmiddle2Have) {
                  _addNiceList(3, 6, 3, 6);
                }
                if (xmiddle3Have) {
                  _addNiceList(6, 9, 3, 6);
                }
                if (xbottom1Have) {
                  _addNiceList(0, 3, 6, 9);
                }
                if (xbottom2Have) {
                  _addNiceList(3, 6, 6, 9);
                }
                if (xbottom3Have) {
                  _addNiceList(6, 9, 6, 9);
                }

                setState(() {});

                //  测试 通关弹窗
                // GamePageUtils().travelEndGame(
                //     context, originalCurrentScore!, isGem, grade!,
                //     gemList: CopaygemList, callbacks: (index) {
                //   grade = index;
                //   startNewGame();
                //   setState(() {
                //     isEndGame = false;
                //   });
                // });
                // 测试 失败弹窗
                // GamePageUtils().TravelGameFail(
                //   context,
                //   currentScore!,
                //   isGem,
                //   gemList: gemList,
                //   callbacks: (selectIndex) {
                //     //游戏结束后，再进行新游戏的设置
                //     startNewGame();
                //     setState(() {
                //       isEndGame = false;
                //     });
                //   },
                // );
              });
            }
          },
          onDragCompleted: () {
            // print("手指放开时进入棋盘了结束.");
          },
          onDraggableCanceled: (Velocity velocity, Offset offset) {
            // print("手指放开时没有进入棋盘结束");
          },

          onDragUpdate: (DragUpdateDetails details) {
            //固定的棋盘
            RenderBox? renderBox =
                anchorKey.currentContext?.findRenderObject() as RenderBox?;
            Offset? boardoffset = renderBox?.localToGlobal(Offset.zero);
            var boardoffsetSize = renderBox?.size;
            //拖动时
            RenderBox? renderBox2 =
                anchorKey2.currentContext?.findRenderObject() as RenderBox?;
            Offset? randomOffset = renderBox2?.localToGlobal(Offset.zero);
            if (boardoffset != null && randomOffset != null) {
              //  print("棋盘上边固定.${boardoffset.dy}"); //有内边句，加上
              double boxhight = CommUtils.getSize(context).height;
              // //棋盘topY坐标 算法 : 棋盘y坐标-每个方块一半  目的拖动进入棋盘一半就要执行代码
              double boardTopY = boardoffset.dy - (boxhight * 1 / 2);

              //棋盘最底部的y坐标值 算法：棋盘高度+y坐标值==棋盘最底部到屏幕最顶部的y坐标值   .-每个格子的一半  目的拖动进入棋盘一半就要执行代码
              double boarbBottonY =
                  boardoffsetSize!.height + boardoffset.dy - (boxhight * 1 / 2);
              // print("下边固定y坐标." + boarbBottonY.toString());

              //    print("移动的高." + (randomOffset.dy).toString());
              //   print("棋盘底部高:${boardTopY}");
              //棋盘右边X坐标 算法   棋盘宽度+棋盘的x
              double boarbrightX =
                  boardoffsetSize.width + boardoffset.dx - (boxhight * 1 / 2);
              //移动坐标在棋盘内
              if (randomOffset.dy >= boardTopY &&
                  randomOffset.dy <= boarbBottonY &&
                  randomOffset.dx >= 0 &&
                  randomOffset.dx <= boarbrightX) {
                //2拿纵向索引
                int y = -1;
                if (randomOffset.dx < boardoffset.dx) {
                  //从棋盘左边进入
                  if (randomOffset.dx >= boardoffset.dx - (boxhight * 1 / 2)) {
                    y = 0;
                  }
                } else {
                  double padingx = randomOffset.dx - screenwight * 0.03;

                  if (padingx >= 0) {
                    double newx = padingx / boxhight;
                    y = newx.toInt(); //不要四舍五入了，否则从右边进入一半就没蒙版效果了
                    if (y > 8) {
                      y == 8;
                    }
                    //    print("纵向坐标值:" + y.toString());
                  }
                }

                int x = -1;
                //3拿排索引
                if (randomOffset.dy < boardoffset.dy) {
                  //拖动的在棋盘顶部
                  if (randomOffset.dy >= boardoffset.dy - (boxhight * 1 / 2)) {
                    x = 0;
                  }
                } else {
                  //拖动的在棋盘中间
                  double toppading = randomOffset.dy - boardoffset.dy;
                  if (toppading >= 0) {
                    double newy = toppading / boxhight;
                    x = newy.round(); //四舍5入

                    if (x > 8) {
                      x == 8;
                    }
                    //   print("横向坐标值:" + x.toString());
                  }
                }

                if (x > -1 && y > -1) {
                  //拿到棋盘x,y标值后
                  Block? block = _randowList[onclickPositon]; //当前拖动的方块
                  List<List<BlockBean>> currentlist = block.shape;
                  bool isBack = false;
                  shine = false;
                  clearMap();

                  for (int i = 0; i < currentlist.length; i++) {
                    //i固定为 0》1,2
                    //随图案是一个二维数组
                    for (int j = 0; j < currentlist[i].length; j++) {
                      if (currentlist[i][j].normal == 1) {
                        //当前拖动的方块
                        //   print("拖动方块坐标值:" + i.toString() + "," + j.toString());

                        int newx = x + i; //X拖动木块的最左边所在索引
                        int newy = y + j; //Y拖动木块的最上边所在索引
                        if (newx > GAME_PAD_MATRIX_H - 1) {
                          clearMap();
                          //只要有一个有方块，就不成立，
                          isBack = true;
                          break;
                          //证明拖动方块有牌数在棋盘的底部外面
                          //   print("没有合适的排超过屏幕");
                        } else if (newy > GAME_PAD_MATRIX_W - 1) {
                          clearMap();
                          //只要有一个有方块，就不成立，
                          isBack = true;
                          break;
                          //证明拖动方块有牌数在棋盘的右边外面
                          //  print("没有y合适的竖超过外面");
                        } else {
                          //正常逻辑
                          BlockBean dataBean = _data[newx][newy];
                          if (dataBean.normal != 1) {
                            //虚拟添加此位置的方格填充状态，方便下一步计算满足消分的蒙版效果
                            mengdata[newx][newy].normal = 1;
                            //给将要满足消分的方格添加蒙版，
                            // List<List<BlockBean>> newdata = _data;
                            //此方格没有模块可以添加
                            //棋盘的横索引int
                            HashMap<int, HashMap<int, BlockBean>> acrosslMap =
                                HashMap();
                            //棋盘的竖索引int
                            HashMap<int, BlockBean> map = HashMap();
                            map[newy] = currentlist[i][j]; //树索引
                            acrosslMap[newx] = map; //横索引
                            shine = true;
                            bgChangelist.add(acrosslMap);
                          } else {
                            clearMap();
                            //只要有一个有方块，就不成立，
                            isBack = true;
                            break;
                          }

                          // print("正常坐标:" +
                          //     newx.toString() +
                          //     "=" +
                          //     dataBean.img +
                          //     ",,," +
                          //     newy.toString() +
                          //     "=" +
                          //     dataBean.img);

                        }

                        // print("加后:" + newx.toString() + "," + newy.toString());

                      }
                    } //内循环
                    if (isBack) {
                      clearMap();
                      break;
                    }
                  } //外循环

                }
                //拖动时在棋盘内的逻辑
              } else {
                //拖动时在棋盘外的逻辑
                clearMap();
              }

              //如果允许放入格子的话 ，查询是否可以消分了。
              if (bgChangelist.length > 0) {
                addScore(false, mengdata);
              }

              setState(() {});
            }
          },
        );
      },
    );
  }

/**
 * 添加九宫格 iCount 
 */
  void _addNiceList(int yStart, int yEnd, int iStart, int iEnd) {
    RenderBox? renderBox =
        anchorKey.currentContext?.findRenderObject() as RenderBox?;
    Offset? boardoffset = renderBox?.localToGlobal(Offset.zero);
    var boardoffsetSize = renderBox?.size;
    //每个格子的宽度
    double size = CommUtils.getSize(context).height;
    double leftx = boardoffset!.dx;
    //棋盘最底部的离窗口底部的距离
    double bottomy = CommUtils.getHeight(context) -
        (boardoffsetSize!.height + boardoffset.dy);

    for (int i = yStart; i < yEnd; i++) {
      for (int y = iStart; y < iEnd; y++) {
        _addShowList(3, Offset(leftx + i * size, bottomy + ((8 - y) * size)));
      }
    }
  }

  /**
   * 添加消分动销
   */
  void _addShowList(int type, Offset offset) {
    var popBean = PopBean();
    popBean.type = type;
    // 横排的话底边距不变。
    popBean.offset = offset;
    addshow.add(popBean);
  }

  /**
   *  给将要待消分格子添加蒙版 isgetScore=tue游戏结束的时候
   */
  // int gemCountAll = 0; //本次得到的宝石总数量

  bool isHaveXiao = false; //true=消分了
  HashMap<String, int> map = HashMap(); //String=xy类索引，以免重复计算宝石数量

  HashMap<int, int> pickUpMap = HashMap(); //本次消分不同宝石捡起的数量. int种类宝石的索引，int数量
  int addScore(bool isgetScore, List<List<BlockBean>> datas) {
    int currentIntegral1 = 0; //横竖排当前积分
    //拖动的时候，把9个消分中格子晴空
    xtop1.clear();
    xtop2.clear();
    xtop3.clear();
    xmiddle1.clear();
    xmiddle2.clear();
    xmiddle3.clear();
    xbottom1.clear();
    xbottom2.clear();
    xbottom3.clear();
    map.clear();
    isHaveXiao = false;
    addshow.clear();
    double leftx = 0;
    double bottomy = 0;
    double size = 0;
    if (isgetScore) {
      // 棋盘的坐标值
      RenderBox? renderBox =
          anchorKey.currentContext?.findRenderObject() as RenderBox?;
      Offset? boardoffset = renderBox?.localToGlobal(Offset.zero);
      var boardoffsetSize = renderBox?.size;

      //每个格子的宽度
      size = CommUtils.getSize(context).height;
      //   double halfSzie = size * 1 / 3;
      leftx = boardoffset!.dx;
      //棋盘最底部的离窗口底部的距离
      bottomy = CommUtils.getHeight(context) -
          (boardoffsetSize!.height + boardoffset.dy);
    }

    for (int x = 0; x < GAME_PAD_MATRIX_H; x++) {
      //竖线索引
      int xcount = 0;
      int threeCount = 0;
      // int gemCount = 0; //宝石横排数量
      for (int y = 0; y < GAME_PAD_MATRIX_W; y++) {
        if (y == 0 || y == 3 || y == 6) {
          //走到9个宫格的开头竖索引，清空
          threeCount = 0;
        }

        if (datas[x][y].normal == 1) {
          xcount = xcount + 1;
          //第一竖
          if (y >= 0 && y <= 2) {
            threeCount = threeCount + 1;
            if (threeCount == 3) {
              if (x >= 0 && x <= 2) {
                xtop1[x] = y;
              } else if (x >= 3 && x <= 5) {
                xmiddle1[x] = y;
              } else if (x >= 6 && x <= 8) {
                xbottom1[x] = y;
              }
            }
            //第2竖
          } else if (y >= 3 && y <= 5) {
            threeCount = threeCount + 1;
            if (threeCount == 3) {
              if (x >= 0 && x <= 2) {
                xtop2[x] = y;
              } else if (x >= 3 && x <= 5) {
                xmiddle2[x] = y;
              } else if (x >= 6 && x <= 8) {
                xbottom2[x] = y;
              }
            }
            //第3竖
          } else if (y >= 6 && y <= 8) {
            threeCount = threeCount + 1;
            if (threeCount == 3) {
              if (x >= 0 && x <= 2) {
                xtop3[x] = y;
              } else if (x >= 3 && x <= 5) {
                xmiddle3[x] = y;
              } else if (x >= 6 && x <= 8) {
                xbottom3[x] = y;
              }
            }
          }

          if (xcount == GAME_PAD_MATRIX_W) {
            //证明这条横排上方格填满了
            isHaveXiao = true;
            double y2 = bottomy + ((8 - x) * size);
            currentIntegral1 = currentIntegral1 + 1;
            for (int i = 0; i < GAME_PAD_MATRIX_W; i++) {
              if (isgetScore) {
                _addShowList(0, Offset(leftx + i * size, y2));
              }

              if (isgetScore &&
                  datas[x][i].normal == 1 &&
                  datas[x][i].gem > 0) {
                //记录此宝石已经被添加后，后续不要再添加了
                if (map['$x$i'] == null) {
                  map['$x$i'] = i;
                  //宝石种类的索引就是
                  var positon = datas[x][i].gem - 1;
                  if (pickUpMap[positon] != null) {
                    pickUpMap[positon] = pickUpMap[positon]! + 1;
                  } else {
                    pickUpMap[positon] = 1;
                  }
                  print("横排索引${positon},值是${pickUpMap[positon]}");
                }
              }
              datas[x][i].normal = 2;
              datas[x][i].eliminationEffect = 1;
              //拖动时增加横排添加蒙版
              addScoreMeng(isgetScore, x, i, datas);
            }
          }
        } else {
          datas[x][y].eliminationEffect = 0;
          datas[x][y].normal = 0;
          datas[x][y].gem = 0;
        }
      }
    }

    // 查询这条竖上是否都有方格填满
    for (int y = 0; y < GAME_PAD_MATRIX_W; y++) {
      //竖线索引
      int xcount = 0;
      for (int x = 0; x < GAME_PAD_MATRIX_H; x++) {
        //1.检查竖型是否满足
        if (datas[x][y].normal != 0) {
          //因为上面做横向判断可能变成2，所以只要不等于0就满足
          xcount = xcount + 1;
          if (xcount == GAME_PAD_MATRIX_H) {
            currentIntegral1 = currentIntegral1 + 1;
            isHaveXiao = true;
            //证明这条竖排上方格填满了
            double x2 = leftx + y * size;
            for (int i = 0; i < GAME_PAD_MATRIX_W; i++) {
              if (isgetScore) {
                _addShowList(1, Offset(x2, bottomy + i * size));
              }

              if (isgetScore &&
                  datas[i][y].normal == 1 &&
                  datas[i][y].gem > 0) {
                //记录此宝石已经被添加后，后续不要再添加了
                if (map['$i$y'] == null) {
                  map['$i$y'] = i;
                  var positon = datas[i][y].gem - 1;

                  if (pickUpMap[positon] != null) {
                    pickUpMap[positon] = pickUpMap[positon]! + 1;
                  } else {
                    pickUpMap[positon] = 1;
                  }
                  print("竖排索引${positon},值是${pickUpMap[positon]}");
                }
              }

              datas[i][y].normal = 2;
              datas[i][y].eliminationEffect = 1;
              //拖动时，增加竖蒙版
              addScoreMeng(isgetScore, i, y, datas);
            }
          }
        } else {
          datas[x][y].normal = 0;
          datas[x][y].eliminationEffect = 0;
        }

        //2.检查9个小格子
        if (datas[y][x].normal != 0) {
          //因为是9宫格，所以这里可以写死，如果棋盘宽度和高度不一样，就不能用此方法了
          //第一竖
          if (x >= 0 && x <= 2) {
            if (xtop1.length > 2) {
              if (y >= 0 && y <= 2) {
                //0-行索引
                print("xop1");
                datas = changData(isgetScore, y, x, datas);
              }
            }
            if (xmiddle1.length > 2) {
              if (y >= 3 && y <= 5) {
                //3-5行
                print("middle11");
                datas = changData(isgetScore, y, x, datas);
              }
            }

            if (xbottom1.length > 2) {
              if (y >= 6 && y <= 8) {
                //6-8行
                print("xbottom1");
                datas = changData(isgetScore, y, x, datas);
              }
            }
            //第二竖
          } else if (x >= 3 && x <= 5) {
            if (xtop2.length > 2) {
              if (y >= 0 && y <= 2) {
                print("xop2");
                datas = changData(isgetScore, y, x, datas);
              }
            }
            if (xmiddle2.length > 2) {
              if (y >= 3 && y <= 5) {
                print("middle2");
                datas = changData(isgetScore, y, x, datas);
              }
            }

            if (xbottom2.length > 2) {
              if (y >= 6 && y <= 8) {
                print("xbottom2");
                datas = changData(isgetScore, y, x, datas);
              }
            }
            //第三竖
          } else if (x >= 6 && x <= 8) {
            if (xtop3.length > 2) {
              if (y >= 0 && y <= 2) {
                print("xop3");
                datas = changData(isgetScore, y, x, datas);
              }
            }
            if (xmiddle3.length > 2) {
              if (y >= 3 && y <= 5) {
                print("middle3");
                datas = changData(isgetScore, y, x, datas);
              }
            }

            if (xbottom3.length > 2) {
              if (y >= 6 && y <= 8) {
                print("xbottom3");
                datas = changData(isgetScore, y, x, datas);
              }
            }
          }
        }
      }
    }

    if (isgetScore) {
      _data = datas;
      mengdata = CommUtils.copyWithList(_data);
    }

    return currentIntegral1;
  }

  /**
   * 增加分数蒙版
   */
  void addScoreMeng(
      bool isgetScore, int x, int y, List<List<BlockBean>> datas) {
    //拖动时，添加蒙版
    if (isgetScore == false) {
      HashMap<int, HashMap<int, BlockBean>> acrosslMap = HashMap();
      //棋盘的竖索引int
      HashMap<int, BlockBean> map = HashMap();
      map[y] = datas[x][y]; //树索引
      acrosslMap[x] = map; //横索引
      scoreChangelist.add(acrosslMap);
    }
  }

  List<List<BlockBean>> changData(
      bool isgetScore, int x, int y, List<List<BlockBean>> datas) {
    if (isgetScore) {
      if (datas[x][y].normal == 1 && datas[x][y].gem > 0) {
        //记录此宝石已经被添加后，后续不要再添加了
        if (map['$x$y'] == null) {
          map['$x$y'] = y;
          var positon = datas[x][y].gem - 1;

          if (pickUpMap[positon] != null) {
            pickUpMap[positon] = pickUpMap[positon]! + 1;
          } else {
            pickUpMap[positon] = 1;
          }
          print("九宫格索引${positon},值是${pickUpMap[positon]}");
        }
      }
      datas[x][y].normal = 2;
      datas[x][y].eliminationEffect = 1;
    } else {
      //33333竖9个九宫格蒙版
      addScoreMeng(isgetScore, x, y, datas);
    }
    isHaveXiao = true;
    return datas;
  }

  //连击次数
  int adjacentMultiple = 0;

  //满足消分的总个数
  // int fractionCount = 0;
  bool shine = false; //true表示闪耀
  void clearMap() {
    //  fractionCount = 0;
    shine = false;
    bgChangelist.clear();
    pickUpMap.clear();
    scoreChangelist.clear();
    mengdata = CommUtils.copyWithList(_data);
    xtop1.clear();
    xtop2.clear();
    xtop3.clear();
    xmiddle1.clear();
    xmiddle2.clear();
    xmiddle3.clear();
    xbottom1.clear();
    xbottom2.clear();
    xbottom3.clear();
  }

  //相邻的九宫格，下次要*2
  bool xtop1Have = false;
  bool xtop2Have = false;
  bool xtop3Have = false;
  bool xmiddle1Have = false;
  bool xmiddle2Have = false;
  bool xmiddle3Have = false;
  bool xbottom1Have = false;
  bool xbottom2Have = false;
  bool xbottom3Have = false;

  HashMap<int, int> xtop1 = HashMap();
  HashMap<int, int> xtop2 = HashMap();
  HashMap<int, int> xtop3 = HashMap();
  HashMap<int, int> xmiddle1 = HashMap();
  HashMap<int, int> xmiddle2 = HashMap();
  HashMap<int, int> xmiddle3 = HashMap();
  HashMap<int, int> xbottom1 = HashMap();
  HashMap<int, int> xbottom2 = HashMap();
  HashMap<int, int> xbottom3 = HashMap();

  ////给将要满足填充条件的格子添加蒙版。。  int 棋盘的行索引  ，  int 棋盘的竖索引
  List<HashMap<int, HashMap<int, BlockBean>>> bgChangelist = [];

  //给将要满足消分条件的格子添加蒙版。  int 棋盘的行索引  ，  int 棋盘的竖索引
  List<HashMap<int, HashMap<int, BlockBean>>> scoreChangelist = [];

  HashMap<int, String> rondowRemowMap = HashMap(); //临时保存随机图案放入棋盘后，以便将随机团隐藏掉，

  //满足消分，  int 棋盘的行索引  ，  int 棋盘的竖索引
  HashMap<int, HashMap<int, BlockBean>> fractionMap = HashMap();

/**
 *   fixCount 比率  每个随机图片的排列方式
 */

  Widget getItem(List<List<BlockBean>> initialRandom, double fixCount,
      bool iskey, int currentPostion) {
    if (rondowRemowMap[currentPostion] != null) {
      return Container();
    } else {
      return getItem2(initialRandom, fixCount, iskey);
    }
  }

  Widget getItem2(
      List<List<BlockBean>> initialRandom, double fixCount, bool iskey) {
    var width = CommUtils.getWidth(context);
    if (iskey) {
      //放大的随机图
      return Padding(
        padding: EdgeInsets.only(left: 10, top: 0, right: 5, bottom: 0),
        child: Column(
          key: anchorKey2,
          //3竖
          children: initialRandom.map((list) {
            return Row(
              //2排
              children: list.map((b) {
                return randomBrik.normal(b, fixCount);
              }).toList(),
            );
          }).toList(),
        ),
      );
    } else {
      return Padding(
        padding: EdgeInsets.only(
          left: 30, //这里写死，为了web拖动适配
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(child: SizedBox()),
            Column(
              //3竖
              children: initialRandom.map((list) {
                return Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  //2排
                  children: list.map((b) {
                    return randomBrik.normal(b, fixCount);
                  }).toList(),
                );
              }).toList(),
            )
          ],
        ),
      );
    }
  }
}
